package cn.wmw.xyy.mq.listener;

import cn.wmw.xyy.bo.CourseOrderPayBo;
import cn.wmw.xyy.domain.CourseOrder;
import cn.wmw.xyy.service.ICourseOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-course-order-pay-group")
public class TxCourseOrderPayListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            if (arg == null){
                log.error("参数arg为空，本地事务执行缺少参数，执行失败！！！");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder courseOrder = JSON.parseObject(JSON.toJSONString(arg), CourseOrder.class);
            courseOrderService.insertOrderAndOrderItem(courseOrder);
            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        byte[] bytes = (byte[])msg.getPayload();
        if(bytes.length == 0){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        CourseOrderPayBo courseOrderPayBo = JSON.parseObject(new String(bytes, StandardCharsets.UTF_8), CourseOrderPayBo.class);
        String orderNo = courseOrderPayBo.getOrderNo();
        CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);
        if (courseOrder == null){
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
